package com.ruoyi.quality.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.service.ClassificationItemsService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quality.domain.QualityClassificationItems;
import com.ruoyi.quality.domain.bo.QualityClassificationItemsBo;
import com.ruoyi.quality.domain.vo.QualityClassificationItemsVo;
import com.ruoyi.quality.mapper.QualityClassificationItemsMapper;
import com.ruoyi.quality.service.IQualityClassificationItemsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 评价项目Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-05
 */
@RequiredArgsConstructor
@Service
public class QualityClassificationItemsServiceImpl implements IQualityClassificationItemsService, ClassificationItemsService {

    private final QualityClassificationItemsMapper baseMapper;

    /**
     * 查询评价项目
     */
    @Override
    public QualityClassificationItemsVo queryById(Long itemsId){
        return baseMapper.selectVoById(itemsId);
    }

    /**
     * 查询评价项目
     */
    @Override
    public String selectItemsNameById(Long itemsId){
        return baseMapper.selectVoById(itemsId).getItemName();
    }

    /**
     * 查询评价项目
     */
    @Override
    public List<QualityClassificationItemsVo> queryByIds(Collection<Long> itemsIds){
        return baseMapper.selectVoBatchIds(itemsIds);
    }


    /**
     * 查询评价项目列表
     */
    @Override
    public List<QualityClassificationItemsVo> queryList(QualityClassificationItemsBo bo) {
        LambdaQueryWrapper<QualityClassificationItems> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<QualityClassificationItems> buildQueryWrapper(QualityClassificationItemsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<QualityClassificationItems> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getParentId() != null, QualityClassificationItems::getParentId, bo.getParentId());
        lqw.eq(bo.getScore() != null && bo.getScore().compareTo(BigDecimal.ZERO) != 0, QualityClassificationItems::getScore, bo.getScore());
        lqw.like(StringUtils.isNotBlank(bo.getItemName()), QualityClassificationItems::getItemName, bo.getItemName());
        lqw.eq(bo.getPostId() != null, QualityClassificationItems::getPostId, bo.getPostId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), QualityClassificationItems::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增评价项目
     */
    @Override
    public Boolean insertByBo(QualityClassificationItemsBo bo) {
        QualityClassificationItems add = BeanUtil.toBean(bo, QualityClassificationItems.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setItemsId(add.getItemsId());
        }
        return flag;
    }

    /**
     * 修改评价项目
     */
    @Override
    public Boolean updateByBo(QualityClassificationItemsBo bo) {
        QualityClassificationItems update = BeanUtil.toBean(bo, QualityClassificationItems.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(QualityClassificationItems entity){
        //TODO 做一些数据校验,如唯一约束
        try {
            Long parentId = entity.getParentId();
            Long itemsId = entity.getItemsId();
            BigDecimal score = entity.getScore();
            if (parentId != 0L){
                QualityClassificationItems parent = baseMapper.selectById(parentId);
                QualityClassificationItems nowItem = baseMapper.selectById(itemsId);
                BigDecimal total = parent.getScore();
                BigDecimal newScore = total.subtract(nowItem.getScore()).add(score);
                QualityClassificationItems items = BeanUtil.toBean(parent, QualityClassificationItems.class);
                items.setScore(newScore);
                baseMapper.updateById(items);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 批量删除评价项目
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            try {
                ids.forEach(id->{
                    QualityClassificationItems item = baseMapper.selectById(id);
                    Long parentId = item.getParentId();
                    BigDecimal score = item.getScore();
                    if (parentId != 0L){
                        QualityClassificationItems parent = baseMapper.selectById(parentId);
                        BigDecimal total = parent.getScore();
                        BigDecimal newScore = total.subtract(score);
                        QualityClassificationItems items = BeanUtil.toBean(parent, QualityClassificationItems.class);
                        items.setScore(newScore);
                        baseMapper.updateById(items);
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
